package com.genshang.restaurant.impl;

import com.genshang.restaurant.config.MiniProgramComponent;
import com.genshang.restaurant.constant.MiniProgramConstant;
import com.genshang.restaurant.constant.ResultConstant;
import com.genshang.restaurant.result.MiniProgramErrorEnum;
import com.genshang.restaurant.result.ResultBody;
import com.genshang.restaurant.service.IWechatService;
import com.genshang.restaurant.util.MiniProgramUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class WechatServiceImpl implements IWechatService {

    @Autowired
    private MiniProgramComponent miniProgramComponent;

    @Override
    public ResultBody loginByCode(String code) {
        // 1. 先获取用户openId识别用户
        Map<String, Object> requestMap = MiniProgramUtil.getMiniProgramHandler().requestWXLogin(code, miniProgramComponent.getAppid(), miniProgramComponent.getSecret());
        if (requestMap.get(ResultConstant.ERROR_CODE) != null &&
                requestMap.get(ResultConstant.ERROR_CODE) != MiniProgramErrorEnum.SUCCESS.getCode()) {
            //返回非成功值，将错误信息返回
            return ResultBody.error(requestMap.get(ResultConstant.ERROR_CODE).toString(), requestMap.get(ResultConstant.ERROR_MESSAGE).toString());
        }
        // 2. 获取openid后获取Account
        String openid = requestMap.get(MiniProgramConstant.OPENID).toString();
        return ResultBody.success(openid);
    }
}
